<!--
  用户信息模态框组件
  显示已登录用户的个人信息、发布的帖子和评论
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="用户信息"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    @close="handleClose"
  >
    <div class="modal-body">
      <!-- 用户基本信息 -->
      <div class="profile-header">
              <div class="avatar-section">
                <div class="avatar">
                  <span v-if="!userInfo.avatar">
                    {{ userInfo.username?.[0]?.toUpperCase() || 'U' }}
                  </span>
                  <img v-else :src="userInfo.avatar" :alt="userInfo.username" />
                </div>
                <div class="user-info">
                  <h3>{{ userInfo.username }}</h3>
                  <p v-if="userInfo.bio" class="bio">{{ userInfo.bio }}</p>
                  <p v-else class="bio-placeholder">暂无个人简介</p>
                  <div class="user-meta">
                    <span>注册时间：{{ formatDate(userInfo.created_at) }}</span>
                  </div>
                </div>
              </div>
              <el-button type="danger" @click="handleLogout">退出登录</el-button>
            </div>

            <!-- 统计信息 -->
            <el-row :gutter="16">
              <el-col :span="8">
                <el-card shadow="hover" class="stat-card">
                  <el-statistic title="发布的帖子" :value="userPosts.length" />
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover" class="stat-card">
                  <el-statistic title="发表的评论" :value="userComments.length" />
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover" class="stat-card">
                  <el-statistic title="获得点赞" :value="totalLikes" />
                </el-card>
              </el-col>
            </el-row>

            <!-- 内容标签页 -->
            <el-tabs v-model="activeContentTab">
              <el-tab-pane :label="`我的帖子 (${userPosts.length})`" name="posts">

                <!-- 我的帖子列表 -->
                <AsyncState
                  :loading="postsLoading"
                  :error="postsError"
                  :isEmpty="!userPosts.length"
                  emptyMessage="你还没有发布过帖子，快去讨论区发帖吧！"
                  :retry="fetchUserPosts"
                >
                  <div class="posts-list">
                    <InfoCard
                      v-for="post in userPosts"
                      :key="post.id"
                      :title="post.title"
                      :description="truncateText(post.content, 120)"
                      :meta="[
                        { label: '发布时间', value: formatDate(post.created_at) },
                        { label: '点赞', value: post.likes ?? 0 },
                        { label: '回复', value: post.replies?.length ?? 0 },
                      ]"
                      :tags="post.tags"
                      :to="`/forum/${post.id}`"
                      clickable
                    />
                  </div>
                </AsyncState>
              </el-tab-pane>

              <el-tab-pane :label="`我的评论 (${userComments.length})`" name="comments">
                <!-- 我的评论列表 -->
                <AsyncState
                  :loading="commentsLoading"
                  :error="commentsError"
                  :isEmpty="!userComments.length"
                  emptyMessage="你还没有发表过评论"
                  :retry="fetchUserComments"
                >
                  <div class="comments-list">
                    <el-card
                      v-for="comment in userComments"
                      :key="comment.id"
                      class="comment-item"
                      shadow="hover"
                    >
                      <div class="comment-header">
                        <span class="comment-target">
                          {{ getCommentTarget(comment) }}
                        </span>
                        <span class="comment-date">{{ formatDate(comment.created_at) }}</span>
                      </div>
                      <p class="comment-content">{{ comment.content }}</p>
                      <RouterLink
                        v-if="comment.target_type === 'post'"
                        :to="`/forum/${comment.target_id}`"
                        class="view-link"
                        @click="handleClose"
                      >
                        查看帖子 →
                      </RouterLink>
                    </el-card>
                  </div>
                </AsyncState>
              </el-tab-pane>
            </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import {
  ElDialog,
  ElTabs,
  ElTabPane,
  ElCard,
  ElButton,
  ElRow,
  ElCol,
  ElStatistic,
} from 'element-plus'
import { useAuth } from '../composables/useAuth'
import { getCurrentUser, getPosts, getComments } from '../api/client'
import { useAsyncData } from '../composables/useAsyncData'
import { formatDate, truncateText } from '../utils/formatters'
import AsyncState from './AsyncState.vue'
import InfoCard from './InfoCard.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:visible', 'logout'])

const authState = useAuth()
const { user, isAuthenticated } = authState
const activeContentTab = ref('posts')
const userInfo = ref({})

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

// 获取所有帖子，然后过滤出当前用户的
const {
  data: allPosts,
  loading: postsLoading,
  error: postsError,
  execute: fetchUserPosts,
} = useAsyncData(getPosts, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

// 获取所有评论，然后过滤出当前用户的
const {
  data: allComments,
  loading: commentsLoading,
  error: commentsError,
  execute: fetchUserComments,
} = useAsyncData(getComments, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

// 过滤出当前用户的帖子
const userPosts = computed(() => {
  if (!user.value?.username) return []
  return allPosts.value
    .filter((post) => post.author === user.value.username)
    .sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0))
})

// 过滤出当前用户的评论
const userComments = computed(() => {
  if (!user.value?.id) return []
  return allComments.value
    .filter((comment) => comment.author_id === user.value.id)
    .sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0))
})

// 计算总点赞数
const totalLikes = computed(() => {
  return userPosts.value.reduce((sum, post) => sum + (post.likes || 0), 0)
})

// 获取评论目标信息
function getCommentTarget(comment) {
  if (comment.target_type === 'post') {
    const post = allPosts.value.find((p) => p.id === comment.target_id)
    return post ? `回复帖子：${post.title}` : `回复帖子 #${comment.target_id}`
  }
  return `评论 #${comment.target_id}`
}

function handleClose() {
  emit('update:visible', false)
}

function handleLogout() {
  authState.logout()
  userInfo.value = {}
  emit('logout')
  handleClose()
}

// 加载用户信息
async function loadUserInfo() {
  if (!isAuthenticated.value) return
  try {
    const currentUser = await getCurrentUser()
    userInfo.value = currentUser || user.value || {}
  } catch (error) {
    console.error('获取用户信息失败', error)
    userInfo.value = user.value || {}
  }
}

watch(
  () => props.visible,
  async (newVal) => {
    if (newVal && isAuthenticated.value) {
      await loadUserInfo()
      await fetchUserPosts()
      await fetchUserComments()
    }
  },
)

onMounted(async () => {
  if (props.visible && isAuthenticated.value) {
    await loadUserInfo()
    await fetchUserPosts()
    await fetchUserComments()
  }
})
</script>

<style scoped>

.modal-body {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.1), rgba(103, 194, 58, 0.1));
  border-radius: 12px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.avatar-section {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  flex: 1;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #67c23a);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32px;
  font-weight: 600;
  flex-shrink: 0;
  overflow: hidden;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.user-info h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2d3d;
}

.bio {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.bio-placeholder {
  margin: 0;
  color: #909399;
  font-style: italic;
  font-size: 14px;
}

.user-meta {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #909399;
}


.stat-card {
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

:deep(.el-statistic__head) {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

:deep(.el-statistic__number) {
  font-size: 28px;
  font-weight: 700;
  color: #409eff;
}

.posts-list,
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.comment-item {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.comment-target {
  font-size: 14px;
  font-weight: 500;
  color: #409eff;
}

.comment-date {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.comment-content {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.view-link {
  align-self: flex-start;
  font-size: 13px;
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
}

.view-link:hover {
  text-decoration: underline;
}

:deep(.el-dialog__body) {
  padding: 20px 24px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: stretch;
  }

  :deep(.el-col) {
    margin-bottom: 12px;
  }

  .avatar-section {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
}
</style>

